package com.atguigu.spzx.cart.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.cart.service.CartService;
import com.rabbitmq.client.Channel;
import com.spzx.cart.domain.CartInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class SpzxCartMqListener {
    @Resource
    CartService cartService;
    //提交订单成功 删除购物车选中购物项
    //"spzx.order.submmit.exchange",
    // "spzx.order.submit.msg"
    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value="spzx.order.submmit.exchange",
                        type = ExchangeTypes.TOPIC),
                    value = @Queue("spzx.cart.order.submit.queue"), //购物车服务接收提交订单消息的 队列
                    key = "spzx.order.submit.msg"
            )
    })
    public void clearCart(Message message , Map<String,Object> map , Channel channel) throws IOException {
        try {
            //删除购物车中选中的购物项
            Long userId = Long.parseLong(map.get("userId").toString());
            cartService.deleteCheckedCartInfos(userId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            if(message.getMessageProperties().isRedelivered()){
                //日志记录丢弃的消息
                log.error("spzx-cart删除购物车选中购物项失败,消息内容:{}" , JSON.toJSONString(map));
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
        }
    }
}
